package cn.tedu.service;

import cn.tedu.bo.*;
import cn.tedu.param.IdCardParam;
import cn.tedu.param.WorkerCreateParam;
import cn.tedu.repository.WorkerAreaRepository;
import cn.tedu.repository.WorkerCategoryRepository;
import cn.tedu.repository.WorkerRepository;
import com.tarena.passport.protocol.LoginUser;
import com.tarena.passport.sdk.context.SecurityContext;
import com.tarena.tp.attach.server.client.AttachApi;
import com.tarena.tp.attach.server.dto.AttachDTO;
import com.tarena.tp.attach.server.param.AttachUpdateParam;
import com.tarena.tp.attach.server.query.AttachQuery;
import com.tarena.tp.luban.account.server.client.AccountApi;
import com.tarena.tp.luban.account.server.dto.AccountDTO;
import com.tarena.tp.luban.worker.server.common.enums.AuditStatusEnum;
import com.tedu.inn.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class WorkerService {

    /**
     *  保证一个userId申请入住师傅，在驳回申请之后，可以重新申请填写入住
     *  同一个用户不止一次调用入住申请，无论多少次入住，只能保存最后一次入住的数据，也就是保证幂等
     */

    @Autowired
    private WorkerRepository workerRepository;

    @Autowired
    private WorkerAreaRepository workerAreaRepository;

    @Autowired
    private WorkerCategoryRepository workerCategoryRepository;

    //完成rpc接口的注入
    @Autowired
    private AttachApi attachApi;

    @Autowired
    private AccountApi accountApi;


    public Long create(WorkerCreateParam workerCreateParam) throws Exception{
        workerCreateParam.setUserId(getUserIdFromJwt());
        // 校验idCard phone
        checkPhoneAndIdCard(workerCreateParam);
        //师傅录入
        Long workerId = saveWorker(workerCreateParam);
        //新增worker_area
        saveWorkerAreas(workerCreateParam);
        //新增worker_category
        saveWorkerCategory(workerCreateParam);
        return workerId;

    }

    private void checkPhoneAndIdCard(WorkerCreateParam workerCreateParam) {
        log.info("身份证和手机号验证通过");
    }

    private void saveWorkerCategory(WorkerCreateParam workerCreateParam) {

        workerCategoryRepository.deleteCategory(workerCreateParam.getUserId());

        workerCategoryRepository.saveCategory(workerCreateParam);
    }

    private void saveWorkerAreas(WorkerCreateParam workerCreateParam) {

        workerAreaRepository.deleteAreas(workerCreateParam.getUserId());

        workerAreaRepository.saveAreas(workerCreateParam);

    }

    public Long saveWorker(WorkerCreateParam workerCreateParam){
        workerRepository.deleteWorker(workerCreateParam.getUserId());
        Long workerId=workerRepository.saveWorker(workerCreateParam);
        //准备一个封装修改信息的集合
        ArrayList<AttachUpdateParam> attachUpdateParams = new ArrayList<>();
        //获取新增的师傅信息中，关于证件图片的列表
        List<IdCardParam> attachList = workerCreateParam.getAttachList();
        //遍历每一张图片信息
        for (IdCardParam idCardParam : attachList) {
            AttachUpdateParam attachUpdateParam = new AttachUpdateParam();
            //图片编号上传至文件id（就是为了根据文件的ID来修改图片的信息）
            attachUpdateParam.setId(idCardParam.getId());
            //设置 是否是封面 1 表示不是
            attachUpdateParam.setIsCover(1);
            //图片业务类型的指定
            attachUpdateParam.setBusinessType(100);
            //图片所属用户
            attachUpdateParam.setBusinessId(workerCreateParam.getUserId().intValue());
            //将封装对象添加到集合中
            attachUpdateParams.add(attachUpdateParam);

        }

        //删除多余图片，保证图片幂等，删除当前bizId+bizType 曾经绑定过的图片
        AttachUpdateParam attachUpdateParam = new AttachUpdateParam();
        //提供userId
        attachUpdateParam.setBusinessId(workerCreateParam.getUserId().intValue());
        //提供业务类型
        attachUpdateParam.setBusinessType(100);
        //调用RPC接口进行图片删除
        attachApi.deleteAttachByBusinessIdAndBusinessType(attachUpdateParam);
        //完成图片的业务数据绑定
        attachApi.batchUpdateAttachByIdList(attachUpdateParams);
        return workerId;
    }

    private Long getUserIdFromJwt() throws Exception{
        LoginUser loginToken = SecurityContext.getLoginToken();
        if (loginToken==null || loginToken.getUserId() == null){
            throw new BusinessException("-1","用户没有登陆");
        }
        return loginToken.getUserId();
    }

    public WorkerBO detail() throws Exception {
        //获取用户ID
        Long userId=getUserIdFromJwt();
        //查询师傅对象 workerBO
        WorkerBO workerBO=workerRepository.findWorker(userId); //20ms
        //判断师傅是否存在，直接返回结果，
        if (workerBO==null || workerBO.getId()== null) {
            //如果为空，则表示用户没有入住师傅
            workerBO=new WorkerBO();
            //审核状态设置为3
            workerBO.setAuditStatus(AuditStatusEnum.UNCREATED.getValue());
            //accountBO 总金额返回为0
            AccountBO accountBO = new AccountBO();
            accountBO.setTotalAmount(0L);
            workerBO.setAccountBO(accountBO);
        }else {
            //查询师傅服务区域 workerAreaBO
            List<WorkerAreaBO> areaBOS=workerAreaRepository.findAreas(userId);//20ms
            workerBO.setWorkerAreaBOList(areaBOS);
            //查询师傅服务种类 workerCategoryBO
            List<WorkerCategoryBO> categoryBOS=workerCategoryRepository.findCategories(userId);//20ms
            workerBO.setWorkerCategoryBOList(categoryBOS);
            //查询师傅证件图片 当类型等于100时 结合userId进行查询
            List<AttachInfoBO> attachInfoBOS=getWorkerAttach(100,userId);
            workerBO.setAttachInfoBOList(attachInfoBOS);
            //查询师傅账户信息
            //accountBO 总金额返回为0  //50ms
            //TODO 远程调用account
//            AccountBO accountBO = new AccountBO();
//            accountBO.setTotalAmount(12345678L);
            AccountDTO accountDTO = accountApi.getAccountByUserId(userId);
            AccountBO accountBO = new AccountBO();
            accountBO.setTotalAmount(accountDTO.getTotalAmount());
            workerBO.setAccountBO(accountBO);
            if (workerBO.getAuditStatus()==0){
                workerBO.setRejectReason("资质不全");
            }
        }
        return workerBO;

    }

    private List<AttachInfoBO> getWorkerAttach(int bussinessType, Long userId) {
        AttachQuery attachQuery = new AttachQuery();
        attachQuery.setBusinessId(userId.intValue());
        attachQuery.setBusinessType(bussinessType);
        List<AttachDTO> attachDTOS = attachApi.getAttachInfoByParam(attachQuery);//50ms
        ArrayList<AttachInfoBO> attachInfoBOS = new ArrayList<>();
        String urlPerfix="http://localhost:8092/static/";
        //http://localhost:8092/static/{file_uuid}
        for (AttachDTO attachDTO : attachDTOS) {
            String fileUuid = attachDTO.getFileUuid();
            String url=urlPerfix+fileUuid;
            AttachInfoBO attachInfoBO = new AttachInfoBO();
            attachInfoBO.setUrl(url);
            attachInfoBOS.add(attachInfoBO);
        }
        return attachInfoBOS;
    }
}
